<template>
  <div>
      <p>商品清单如下：</p>
    <p v-for="item in arr" :key="item.shopName">
          {{item.shopName}} {{item.price}}元/份
      </p>
        <br>
      请选择购买数量：
        <br>
        <br>
         <p v-for="(item,index) in arr" :key="index">
          {{item.shopName}}
           <button @click="add(index)">+</button>
           {{item.count}}
           <Minus
           :arr="arr"
           :index="index"
           @onlose="lose"
           />
      </p>
           <br>
           <p>总价为：{{ total }}</p>
  </div>
</template>

<script>
    // 引用减号组件
    import Minus from './components/Minus.vue'
export default {
    name:'App',
    components:{
        Minus
    },
    data(){
        return {
            total:'0.00',
            arr:[
    {
        "shopName": "可比克薯片",
        "price": 5.515,
        "count": 0
    },
    {
        "shopName": "草莓酱",
        "price": 3.5,
        "count": 0
    },
    {
        "shopName": "红烧肉",
        "price": 55,
        "count": 0
    },
    {
        "shopName": "方便面",
        "price": 12,
        "count": 0
    }
]
        }
    },
    methods:{
        add(index){
            if( this.arr[index].count<0) return
            // 根据索引号让数量自增
            this.arr[index].count++;
        },
        lose(index){
             if( this.arr[index].count<=0) return
           // 根据索引号让数量自减
            this.arr[index].count--;  
        }
    },
    watch:{
        arr:{
    deep:true,
    handler(arr){
        this.total=0;
        arr.forEach(ele=>{
       this.total+=(ele.count*ele.price)
        })
    
      this.total=this.total.toFixed(2)
        return this.total;
    }
        }
    }
}
</script>

<style>
*{
    margin: 0;
    padding: 0;
}
</style>